//
//  ProductSearchsVC.m
//  sensen_ios
//
//  Created by pro on 16/4/25.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "ProductSearchsVC.h"

// 控制器
#import "ShopVC.h" // 商城首页
#import "ShopMessageVC.h" // 消息界面
#import "ProductDetailsVC.h" // 商品详情页面
#import "ProductDetailVC.h"

// 视图
#import "CarouselView.h" // 轮播视图
#import "ShopListHeaderView.h" // 头视图
#import "ShopSortView.h" // 排序视图
#import "ShopFilterView.h" // 筛选视图

// 单元格
#import "ProductCell.h"

// 数据
#import "ProductModel.h" // 商品列表数据

@interface ProductSearchsVC () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UITextFieldDelegate, ShopListHeadViewDelegate, ShopSortViewDelegate, ShopFilterViewDelegate, UITableViewDelegate, UITableViewDataSource>
{
    NSString *_searchName; // 搜索商品关键字
    NSString *_sectionName; // 一级类目名字
    NSString *_subSectionName; // 二级类目名字
    NSString *_sortName; // 排序名字
    NSString *_filterRange; // 查询区间（自己拼接10-20）
    
    
    NSMutableArray *_itemsAry; // 商品数组
    NSInteger _page; // 当前商品的页数
}
// 属性
@property (nonatomic, assign) BOOL isShowMore; // 是否右侧导航栏显示更多

// 视图
@property (nonatomic, strong) UIView *moreView; // 点击导航栏右侧...的时候展示更多

@property (nonatomic, strong) UITableView *tableView; // 表视图
@property (nonatomic, strong) UICollectionView *collectionView; // 商品列表视图

@property (nonatomic, strong) ShopListHeaderView *headerView; // 排序和筛选视图

@end

@implementation ProductSearchsVC 

#pragma mark - 视图方法
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self _createViews];
    [self createSearchBar]; // 创建搜索栏
    [self createLeftBarButtonItemWithImagename:nil]; // 创建左侧返回按钮
    [self createRightBarButtonItemsWithImagenameAry:@[@"下拉菜单按钮"]];
    
    [self _getData];
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    
    // 设置导航栏颜色
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:SS_NAVI_ORANGE_COLOR] forBarMetrics:UIBarMetricsDefault];
    
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];
    // 该控制器返回或者跳转的时候要删除更多视图
    _isShowMore = NO;
    [_moreView removeFromSuperview];
    _moreView = nil;
    
    if (self.view.userInteractionEnabled == NO) {
        self.view.userInteractionEnabled = YES;
    }
    
}
// 右侧按钮的样式可以自定义，由imgname控制，如果是文字则调用下面的接口
- (void)createRightBarButtonItemsWithImagenameAry:(NSArray *)imgnameAry {
    NSMutableArray *itemsAry = [[NSMutableArray alloc] init];
    for (int i = 0; i < imgnameAry.count; i ++) {
        
        UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
        customView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(rightClick:)];
        [customView addGestureRecognizer:tap];
        
        // 图标
        UIImageView *rightButton = [[UIImageView alloc] initWithFrame:CGRectMake((customView.width - 24)/2.0, 3, 24, 24)];
        rightButton.userInteractionEnabled = YES;
        [rightButton setImage:[UIImage imageNamed:imgnameAry[i]]];
        [customView addSubview:rightButton];
        
        UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:customView];
        [itemsAry addObject:rightBarButton];
    }
    self.navigationItem.rightBarButtonItems = itemsAry;
}
// 创建中间的搜索栏
- (void)createSearchBar {
    UIView *searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 50 * 2, 35)];
    searchView.backgroundColor = SS_NAVI_ORANGE_LIGHT_COLOR;
    searchView.layer.cornerRadius = searchView.height / 2.0;
    
    // 搜索
    UIImageView *searchImgView = [[UIImageView alloc] initWithFrame:CGRectMake(8, 8, searchView.height - 16, searchView.height - 16)];
    searchImgView.image = [UIImage imageNamed:@"商城首页_搜索"];
    [searchView addSubview:searchImgView];
    
    // 搜索栏输入框
    UITextField *searchBarTf = [[UITextField alloc] initWithFrame:CGRectMake(searchImgView.right + 5, 2, searchView.width - searchImgView.right - searchView.height / 2, 31)];
    searchBarTf.textColor = [UIColor whiteColor];
    searchBarTf.tintColor = [UIColor whiteColor];
    searchBarTf.returnKeyType = UIReturnKeySearch;
    searchBarTf.delegate = self;
    NSDictionary *stringAttr = @{NSFontAttributeName:[UIFont systemFontOfSize:15],NSForegroundColorAttributeName:[UIColor whiteColor]};
    NSAttributedString *palceholderString = [[NSAttributedString alloc] initWithString:@"搜索" attributes:stringAttr];
    searchBarTf.attributedPlaceholder = palceholderString;
    [searchView addSubview:searchBarTf];
    
    self.navigationItem.titleView = searchView;
}

#pragma mark - 加载数据（简化版）
/**
 *  获得查询商品列表的业务参数
 *
 *  @param sectionName    一级类目的名称
 *  @param subSectionName 二级类目的名称
 *  @param sortName       排序的名称
 *  @param filterRange    筛选的区间
 */
- (NSMutableDictionary *)_getParamsWithSearchName:(NSString *)searchName sortName:(NSString *)sortName filterRange:(NSString *)filterRange {
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    // 无搜索内容直接返回空的参数
    if (searchName == nil || searchName.length == 0) {
        [params setObject:@"" forKey:@"name"];
    } else {
        // 有搜索内容写入参数中
        [params setObject:searchName forKey:@"name"];
    }
    NSString *minPrice, *maxPrice; // 价格区间
    if (filterRange != nil) {
        NSArray *priceRange = [filterRange componentsSeparatedByString:@"-"];
        minPrice = [priceRange firstObject];
        maxPrice = [priceRange lastObject];
    }
    // 本方法中一级类目一定是有的
    if (filterRange == nil) { // 不包含价格区间
        if (sortName != nil ) { // 包含排序
            [params setObject:sortName forKey:@"order"];
        }
    } else { // 包含价格区间的
        [params setObject:minPrice forKey:@"min_cost"];
        [params setObject:maxPrice forKey:@"max_cost"];
        if (sortName != nil ) { // 包含排序
            [params setObject:sortName forKey:@"order"];
        }
    }
    
    NSLog(@"请求参数:%@", params);
    return params;
}
- (void)_getData {
    
    [self.view endEditing:YES];

    // 获得参数
    NSMutableDictionary *params = [self _getParamsWithSearchName:_searchName sortName:_sortName filterRange:_filterRange];
    
    _page = 1; // 加载新数据了，page重置为1
    [params setObject:@(_page) forKey:@"page_no"];
    [params setObject:@(10) forKey:@"page_size"];
    
    [SVProgressHUD showWithStatus:@"请耐心等待..."]; // 请求中
    self.view.userInteractionEnabled = NO;
    [_tableView.footer resetNoMoreData];
    
    [BoyeHttpClient post:@"BY_Product_query" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
        
        // 初始化数据数组
        if (_itemsAry == nil) {
            _itemsAry = [[NSMutableArray alloc] init];
        } else {
            [_itemsAry removeAllObjects];
        }
        
        if (![result[@"list"] isKindOfClass:[NSNull class]]) { // 有数据
            for (NSDictionary *dic in result[@"list"]) {
                ProductModel *model = [[ProductModel alloc] initContentWithDic:dic];
                [_itemsAry addObject:model];
            }
        }
        [_collectionView reloadData]; // 刷新表视图
        
        [self performSelector:@selector(sss) withObject:nil afterDelay:0.001];
        
        [SVProgressHUD dismiss];
        self.view.userInteractionEnabled = YES;
        
        if (_itemsAry.count == [result[@"count"] integerValue]) {
            [_tableView.footer noticeNoMoreData];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"请求失败" withDuration:2];
        self.view.userInteractionEnabled = YES;
        
    }];
}
- (void)_getMoreData {
    
    NSMutableDictionary *params = [self _getParamsWithSearchName:_searchName sortName:_sortName filterRange:_filterRange];
    
    _page += 1; // 请求更多数据，page自增1
    [params setObject:@(_page) forKey:@"page_no"];
    [params setObject:@(10) forKey:@"page_size"];
    
    [BoyeHttpClient post:@"BY_Product_query" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
        if (![result[@"list"] isKindOfClass:[NSNull class]]) { // 有数据
            for (NSDictionary *dic in result[@"list"]) {
                ProductModel *model = [[ProductModel alloc] initContentWithDic:dic];
                [_itemsAry addObject:model];
            }
        }
        
        [_collectionView reloadData]; // 刷新表视图
        
        [self performSelector:@selector(sss) withObject:nil afterDelay:0.001];
        
        if (_itemsAry.count == [result[@"count"] integerValue]) {
            [_tableView.footer noticeNoMoreData];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"请求失败" withDuration:2];
    }];
    
    [_tableView.footer endRefreshing]; // 结束加载更多
}
- (void)sss {
    NSLog(@"推荐商品列表的高度:%lf", _collectionView.contentSize.height);
    if (_collectionView.contentSize.height < 20) {
        _collectionView.contentSize = CGSizeMake(_collectionView.contentSize.width, 0);
    }
    _collectionView.height = _collectionView.contentSize.height;
    [_tableView reloadData];
    
}


#pragma mark - 创建视图
- (void)_createViews {
    
    // 筛选视图们
    [self _createHeaderView]; // 筛选和排序的视图
    
    // 单元格们
    [self _createCollectionView]; // 创建商品列表视图
    
    // 表视图
    [self _createTableView];
    
}

// 筛选和排序的视图
- (void)_createHeaderView {
    _headerView = [[ShopListHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 35)];
    _headerView.firstViewTitle = @"排序";
    _headerView.delegate = self;
}

// 创建商品列表视图
- (void)_createCollectionView {
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 5;
    layout.minimumLineSpacing = 5;
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    CGFloat width = (SCREEN_WIDTH - 5 * 3) / 2.0;
    CGFloat height = width + 30 + 20 + 10;
    // 设置单元格尺寸
    layout.itemSize = CGSizeMake(width, height);
    
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1) collectionViewLayout:layout];
    // 设置代理和数据源方法
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    _collectionView.scrollEnabled = NO;
    
    // 注册单元格
    UINib *nib = [UINib nibWithNibName:@"ProductCell" bundle:nil];
    [_collectionView registerNib:nib forCellWithReuseIdentifier:@"ProductCell"];
    
}
// 创建表视图
- (void)_createTableView {
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    // 下拉加载更多
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(_getMoreData)];
    [footer setTitle:@"搜索更多有趣的商品!" forState:MJRefreshStateNoMoreData];
    _tableView.footer = footer;
    
}



#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}
// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    

    if (indexPath.section == 0) {
        static NSString *listCell = @"listCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:listCell];
        
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:listCell];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            [cell.contentView addSubview:_collectionView];
            
        }
        return cell;
        
    }
    
    return nil;
}
// 设置单元格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        return _collectionView.height;
    }
    
    return 44;
}
// 设置组头高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        switch (_headerView.type) {
            case typeNone:
                return 35;
                break;
            case typeSort:
                return 35 + 120;
                break;
            case typeFilter:
                return 35 + 90;
                break;
            default:
                break;
        }
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        return _headerView;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0;
}
// 单元格点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

#pragma mark - collectionView 代理
// 定义展示的UICollectionViewCell的个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
// 定义展示的Section的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _itemsAry.count;
}
// 每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ProductCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ProductCell" forIndexPath:indexPath];
    cell.model = _itemsAry[indexPath.item];
    return cell;
}

// 单元格选中事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ProductModel *model = _itemsAry[indexPath.item];
    
    // 跳转到详情页面
    ProductDetailsVC *vc = [[ProductDetailsVC alloc] init];
    vc.pid = model.p_id;
    [self.navigationController pushViewController:vc animated:YES];
    
    // 点击进入单元格后，重置筛选的头视图
    [_headerView tapView:typeNone];
    [_tableView reloadData];
}




#pragma mark - 点击事件
- (void)rightClick:(UITapGestureRecognizer *)tap {
    
    if (_moreView == nil) {
        _moreView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 100, 60, 100, 60)];
        _moreView.backgroundColor = [UIColor whiteColor];
        [_APP_KEYWINDOW addSubview:_moreView];
        _moreView.left = SCREEN_WIDTH;
        
        // 商城首页，消息
        NSArray *titles = @[@"商城首页",@"消息"];
        NSArray *imgNames = @[@"下拉菜单回到商城首页",@"下拉菜单消息"];
        for (int i = 0; i < titles.count; i ++) {
            // 总视图，用于点击
            UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, i * _moreView.height / 2.0, _moreView.width, _moreView.height / 2.0)];
            bgView.tag = i + 1;
            [_moreView addSubview:bgView];
            // 添加点击手势
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(naviRightTap:)];
            [bgView addGestureRecognizer:tap];
            // 图片
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 20, 20)];
            imgView.image = [UIImage imageNamed:imgNames[i]];
            [bgView addSubview:imgView];
            // 文字
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(imgView.right + 5, imgView.top, _moreView.width - imgView.width - 10, imgView.height)];
            label.userInteractionEnabled = YES;
            label.font = FONT(14);
            label.text = titles[i];
            label.textColor = [UIColor darkGrayColor];
            label.textAlignment = NSTextAlignmentLeft;
            [bgView addSubview:label];
        }
        
    }
    
    if (!_isShowMore) {
        [UIView animateWithDuration:0.3 animations:^{
            _moreView.left = SCREEN_WIDTH - _moreView.width;
        }];
    } else {
        [UIView animateWithDuration:0.3 animations:^{
            _moreView.left = SCREEN_WIDTH;
        }];
    }
    
    // 转换是否显示
    _isShowMore = !_isShowMore;
}


// 右侧导航栏按钮点击
- (void)naviRightTap:(UITapGestureRecognizer *)tap {
    if (tap.view.tag == 1) {
        // 点击商城首页
        for (UIViewController *vc in self.navigationController.viewControllers) {
            // 找到首页，并返回到首页
            if ([vc isKindOfClass:[ShopVC class]]) {
                [self.navigationController popToViewController:vc animated:YES];
                return;
            }
        }
    } else {
        // 点击消息
        ShopMessageVC *vc = [[ShopMessageVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - 输入框代理事件
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    _searchName = textField.text;
    [self keyboardDown];
    [self _getData];
    
    return YES;
}

#pragma mark - 排序，筛选视图等点击
- (void)headerViewDidSelected:(NSInteger)tag {
    
    [_headerView endEditing:YES];
    
    if (tag == 1) {
        [_headerView tapView:typeSort];
        [_tableView reloadData];
    }
    // 销量优先
    else if (tag == 2) {
        
        _headerView.firstViewTitle = @"排序";
        _headerView.secondTitleUse = YES;
        _sortName = @"11";
        
        [_headerView tapView:typeNone];
        [_tableView reloadData];
        
        // 请求排序后的参数
        [self _getData];
        
    }
    // 筛选
    else {
        [_headerView tapView:typeFilter];
        [_tableView reloadData];
    }
}
- (void)headerSortViewDidChoose:(NSInteger)tag {
    
    NSString *sortText = nil;
    switch (tag) {
        case 1:
        {
            sortText = @"综合排序";
            _sortName = @"10";
        }
            break;
        case 2:
        {
            sortText = @"价格从低到高";
            _sortName = @"12";
        }
            break;
        case 3:
        {
            sortText = @"价格从高到低";
            _sortName = @"13";
        }
            break;
        default:
            break;
    }
    
    _headerView.firstViewTitle = sortText;
    [_headerView tapView:typeNone];
    [_tableView reloadData];
    
    // 查询排序后的商品列表
    [self _getData];
}
- (void)headerFilterViewDidChooseRange:(NSString *)range {
    _filterRange = range;
    [_headerView tapView:typeNone];
    [_tableView reloadData];
    
    // 查询排序后的商品列表
    [self _getData];
}

@end
